package com.corner.presenter.imp;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVInstallation;
import com.corner.model.cornerservice.domain.User;
import com.corner.model.cornerservice.helper.UserHelper;
import com.corner.presenter.IMainPresenter;
import com.corner.presenter.base.BasePresenter;
import com.corner.ui.view.IMainView;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2015/7/11，18.11.
 * 描述：
 */
public class MainPresenter extends BasePresenter<IMainView> implements IMainPresenter {

    @Override
    public void saveInstallationId() {
        Observable.create(new Observable.OnSubscribe<String>() {

            @Override
            public void call(Subscriber<? super String> subscriber) {
                try {
                    AVInstallation.getCurrentInstallation().save();
                    String installationId = AVInstallation.getCurrentInstallation().getInstallationId();
                    subscriber.onNext(installationId);
                } catch (AVException e) {
                    e.printStackTrace();
                }
            }
        }).flatMap(new Func1<String, Observable<User>>() {
            @Override
            public Observable<User> call(String installationId) {
                // 关联  installationId 到用户表等操作……
                User user = User.createWithoutData(User.getCurrentUser().getObjectId(), User.class);
                user.setInstallationId(installationId);
                return UserHelper.saveUser(user);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<User>() {
            @Override
            public void call(User user) {
                if (view != null)
                    view.saveInstallationIdSucess();
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                if (view != null)
                    view.saveInstallationIdError();
            }
        });
    }

}
